const {v4: uuidv4} = require('uuid');
const createModel = require('../mongodb/createModel')
const {getMenuSeq, includeChildren, modifySeq, getMenuInfo, updateSeq} = require('../utils/menu')

// 分类
const schema = {
    // 用户ID
    userId: {type: String, required: true},
    // 菜单ID
    menuId: {type: String, required: true},
    // 菜单父ID
    parentId: {type: String, default: ''},
    // 图标类型 0字体图标 1图片图标
    iconType: {type: Number, required: true, default: 0},
    // 图标
    icon: {type: String, default: ''},
    // 菜单名称
    name: {type: String, required: true, default: '', trim: true},
    // 菜单排序 从小到大
    seq: {type: Number, required: true, default: 0},
    // 创建时间
    createTime: {type: Date, default: Date.now}
}

const model = createModel('menus', schema);

/**
 * 新增菜单
 * @param params    参数(父ID,图标类型,图标,菜单名称)
 * @returns {Promise<object>} 结果
 */
const handleAdd = (params) => {
    return new Promise(async (resolve, reject) => {
        delete params.createTime;
        params.menuId = uuidv4();
        let seqData = await getMenuSeq(model, params);
        params.seq = seqData.max + 1;
        model.create(params, (err, docs) => {
            if (!err) {
                resolve({code: 1, data: null, msg: '新增成功'});
            } else {
                reject({code: 0, data: null, msg: err.message});
            }
        })
    })
}

/**
 * 查询菜单
 * @param userId        用户ID
 * @returns {Promise<object>} 结果
 */
const handleList = ({userId}) => {
    return new Promise((resolve, reject) => {
        model.find({userId}, {_id: 0, __v: 0}).sort({seq: 1}).exec((err, docs) => {
            if (!err) {
                resolve({code: 1, data: docs, msg: '查询菜单成功'});
            } else {
                reject({code: 0, msg: err.message});
            }
        })
    })
}

/**
 * 修改菜单
 * @param params 参数 查询数据(用户ID,菜单ID) 可修改参数(图标类型,图标,菜单名称)
 * @returns {Promise<object>} 结果
 */
const handleModify = (params) => {
    return new Promise((resolve, reject) => {
        const filter = {
            userId: JSON.parse(JSON.stringify(params)).userId,
            menuId: JSON.parse(JSON.stringify(params)).menuId
        }
        delete params.userId;
        delete params.menuId;
        delete params.parentId;
        delete params.seq;
        delete params.createTime;
        model.findOneAndUpdate(filter, params, (err, docs) => {
            if (!err) {
                resolve({code: 1, msg: '操作成功'});
            } else {
                reject({code: 0, msg: err.message});
            }
        })
    })
}


/**
 * 菜单删除
 * @param params  传参    userId, menuId
 * @returns {Promise<object>} 结果
 */
const handleDel = (params) => {
    return new Promise(async (resolve, reject) => {
        let isChildren = await includeChildren(model, params);
        if (isChildren) {
            return reject({code: 0, data: null, msg: '仅能从子菜单进行删除'})
        }
        model.findOneAndDelete({userId: params.userId, menuId: params.menuId}, async (err, docs) => {
            if (!err) {
                if (!docs) {
                    reject({code: 0, data: null, msg: '未查询到菜单信息'});
                } else {
                    const modifySeqResult = await modifySeq(model, docs).catch(error => reject(error));
                    if (modifySeqResult && modifySeqResult.code === 1) {
                        resolve({code: 1, data: null, msg: '删除成功'})
                    }
                }
            } else {
                reject({code: 0, data: null, msg: err.message});
            }
        })
    })
}


/**
 * 修改排序
 * @param params    传参  userId,menuId,direction:1上移 -1下移
 * @returns {Promise<object>} 结果
 */
const handleMove = (params) => {
    return new Promise(async (resolve, reject) => {
        params.direction = Number(params.direction);
        if (params.direction !== 1 && params.direction !== -1 || !params.direction) {
            return reject({code: 0, data: null, msg: '请检查移动方向参数'})
        }
        const menuInfo = await getMenuInfo(model, params);
        if (!menuInfo) {
            return reject({code: 0, data: null, msg: '暂未查到菜单信息'})
        }
        const {seq} = menuInfo;   // 当前菜单的排序
        let seqData = await getMenuSeq(model, menuInfo);
        if (params.direction === 1 && seq === seqData.min) {
            return reject({code: 0, data: null, msg: '无法进行上移排序'})
        }
        if (params.direction === -1 && seq === seqData.max) {
            return reject({code: 0, data: null, msg: '无法进行下移排序'})
        }
        const updateSeqParams = {userId: params.userId, parentId: menuInfo.parentId, seq, direction: params.direction};
        const uploadResult = await updateSeq(model, updateSeqParams).catch(error => reject(error));
        if (uploadResult && uploadResult.code === 1) {
            model.findOneAndUpdate({
                userId: params.userId,
                menuId: params.menuId
            }, {$inc: {seq: -params.direction}}, (err, docs) => {
                if (!err) {
                    resolve(uploadResult)
                } else {
                    reject({code: 0, data: null, msg: err.message});
                }
            })
        }
    })
}

module.exports = {model, handleAdd, handleDel, handleModify, handleList, handleMove}
